# -*- coding: utf-8 -*-
"""
****************************
@Time    : 2021/4/26 8:45
@Author  : Candy
@File    : articles.py
****************************
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import datetime

from flask_sqlalchemy import SQLAlchemy
from sqlconfig import app

db = SQLAlchemy(app)

"""
文章表
0. id
1.编号
2.标题
3.分类
4.作者
5.封面
6.内容
7.发布时间
8.修改时间
9.等级
"""


class SerializrableMixin(object):
    """A SQLAlchemy mixin class that can serialize itself as a JSON object"""

    def to_dict(self):
        """Return dict representation of class by iterating over database columns."""
        value = {}
        for column in self.__table__.columns:
            attribute = getattr(self, column.name)
            if isinstance(attribute, datetime.datetime):
                attribute = str(attribute)
            value[column.name] = attribute
        return value

    def from_dict(self, attributes):
        """Update the current instance base on attribute->value by *attributes*"""
        for attribute in attributes:
            setattr(self, attribute, attributes[attribute])
        return self


class Article(db.Model, SerializrableMixin):
    __tablename__ = "article"
    id = db.Column(db.Integer, primary_key=True)
    aid = db.Column(db.String(100), unique=True)
    title = db.Column(db.String(100), nullable=False, unique=True)
    cate = db.Column(db.Integer, nullable=False)
    user_id = db.Column(db.Integer, nullable=False)
    logo = db.Column(db.Text, nullable=True)
    content = db.Column(db.Text, nullable=False)
    add_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime)
    update_time = db.Column(db.DateTime, nullable=True)
    is_del = db.Column(db.Integer, nullable=True, default=0)
    is_public = db.Column(db.Integer, nullable=True, default=1)
    rate_star = db.Column(db.Integer, nullable=True, default=1)
    tags = db.Column(db.String(512), default='日常分享')
    view_count = db.Column(db.Integer, nullable=True, default=0)

    def __repr__(self):
        return 'Article(name:{}, add_time:{})'.format(self.title, self.add_time)

    def keys(self):
        return ['aid', 'title', 'is_public', 'rate_star']

    def __getitem__(self, item):
        return getattr(self, item)


class Cate(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    cate_value = db.Column(db.String(100), unique=True)
    add_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime)

    def __repr__(self):
        return 'Cate(cate_value:{}, add_time:{})'.format(self.cate_value, self.add_time)


class Img(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    types = db.Column(db.String(100), unique=True)
    img_base64 = db.Column(db.Text, nullable=False)
    
    def __repr__(self):
        return 'Img(types:{}, img_base64:{})'.format(self.types, self.img_base64)


if __name__ == "__main__":
    db.drop_all()
    db.create_all()
